package Service;

import Client.Client;
import Monitor.ClientThread;
import Utils.PacketUtils;
import Utils.ThreadManage;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.concurrent.TimeUnit;

/**
 * The type Send file.
 *
 * @author dzr
 * @version 1.0
 */
public class SendFile {
    /**
     * The constant SEND_FILE.
     */
    public static final int SEND_FILE = 4;

    /**
     * Send file.
     *
     * @param fileType the file type
     * @param filePath the file path
     * @param s_uid    the sender's uid
     * @param r_uid    the receiver's uid
     * @throws IOException the io exception
     */
    public static void sendFile(int fileType, String filePath, int s_uid, int r_uid) throws IOException {
        File source = new File(filePath);
        String fileName = source.getName();
        long fileLength = source.length();
        ClientThread thread = ThreadManage.getInstance().getClientThreads().get(s_uid);
        JSONObject ret2Server = new JSONObject();
        ret2Server.put("fileName", fileName);
        ret2Server.put("fileType", fileType);
        ret2Server.put("cmd", SEND_FILE);
        ret2Server.put("s_uid", s_uid);
        ret2Server.put("s_name", thread.getUsername());
        ret2Server.put("r_uid", r_uid);
        ret2Server.put("fileLength", fileLength);
        DatagramSocket client = thread.getSocket();

        PacketUtils.sendPacket(ret2Server);

        Runnable sendThread = new Runnable(){
            @Override
            public void run() {
                try {
                    InputStream inputstream = new FileInputStream(source);
                    byte[] data = new byte[1024];

                    while ((inputstream.read(data)) != -1) {
                        DatagramPacket pack = new DatagramPacket(data, data.length, Client.server);
                        client.send(pack);
                        TimeUnit.MICROSECONDS.sleep(1);
                    }

                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                }
            }
        };
        sendThread.run();
    }
}
